#include <STC89C5xRC.H>

sbit ds1302_sclk=P3^6;
sbit ds1302_IO=P3^4;
sbit ds1302_CE=P3^5;

char ds1302_time[]={25,8,16,13,59,55,6};

#define ds1302_second  0x80
#define ds1302_minute  0x82
#define ds1302_hour  0x84
#define ds1302_date  0x8a
#define ds1302_month  0x88
#define ds1302_year  0x8c
#define ds1302_day  0x86
#define ds1302_wp  0x8e

unsigned char i = 0;

void ds1302_init()
{
	ds1302_CE=0;
	ds1302_sclk=0;
	//ds1302_IO=0;
}

void ds1302_writebyte(unsigned char command,unsigned char Data)
{
	ds1302_CE=1;
	for(i = 0;i<8;i++)
	{
	ds1302_IO=command&(0x01<<i);
	ds1302_sclk=1;
	ds1302_sclk=0;
	}
	for(i = 0;i<8;i++)
	{
	ds1302_IO=Data&(0x01<<i);
	ds1302_sclk=1;
	ds1302_sclk=0;
	}
	//ds1302_IO=0;
	ds1302_CE=0;

}
unsigned char ds1302_readbyte(unsigned char command)
{
	unsigned char Data=0x00;
	command |=0x01;
	ds1302_CE=1;
	for(i = 0;i<8;i++)
	{
	ds1302_IO=command&(0x01<<i);
	ds1302_sclk=0;
	ds1302_sclk=1;
	}
	for(i = 0;i<8;i++)
	{
		ds1302_sclk=1;
		ds1302_sclk=0;
		if(ds1302_IO){Data|=(0x01<<i);}
	}
	ds1302_IO=0;
	ds1302_CE=0;
	return Data;
 }

 void ds1302_settime()
 {
	ds1302_writebyte(ds1302_wp,0x00);
	ds1302_writebyte(ds1302_year,ds1302_time[0]/10*16+ds1302_time[0]%10);
	ds1302_writebyte(ds1302_month,ds1302_time[1]/10*16+ds1302_time[1]%10);
	ds1302_writebyte(ds1302_day,ds1302_time[2]/10*16+ds1302_time[2]%10);
	ds1302_writebyte(ds1302_hour,ds1302_time[3]/10*16+ds1302_time[3]%10);
	ds1302_writebyte(ds1302_minute,ds1302_time[4]/10*16+ds1302_time[4]%10);
	ds1302_writebyte(ds1302_second,ds1302_time[5]/10*16+ds1302_time[5]%10);
	ds1302_writebyte(ds1302_date,ds1302_time[6]/10*16+ds1302_time[6]%10);
	ds1302_writebyte(ds1302_wp,0x80);
 }
 void ds1302_readtime()
 {
	 unsigned char temp;
	 temp=ds1302_readbyte(ds1302_year);
	 ds1302_time[0] = temp/16*10+temp%16;
	 temp=ds1302_readbyte(ds1302_month);
	 ds1302_time[1] = temp/16*10+temp%16;
	 temp=ds1302_readbyte(ds1302_day);
	 ds1302_time[2] = temp/16*10+temp%16;
	 temp=ds1302_readbyte(ds1302_hour);
	 ds1302_time[3] = temp/16*10+temp%16;
	 temp=ds1302_readbyte(ds1302_minute);
	 ds1302_time[4] = temp/16*10+temp%16;
	 temp=ds1302_readbyte(ds1302_second);
	 ds1302_time[5] = temp/16*10+temp%16;
	 temp=ds1302_readbyte(ds1302_date);
	 ds1302_time[6] = temp/16*10+temp%16;
 
 
 }